package com.edee.bigday.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edee.bigday.commodity.dao.AttrAttrgroupRelationDao;
import com.edee.bigday.commodity.dao.AttrDao;
import com.edee.bigday.commodity.dao.AttrGroupDao;
import com.edee.bigday.commodity.dao.CategoryDao;
import com.edee.bigday.commodity.entity.AttrAttrgroupRelationEntity;
import com.edee.bigday.commodity.entity.AttrEntity;
import com.edee.bigday.commodity.entity.AttrGroupEntity;
import com.edee.bigday.commodity.entity.CategoryEntity;
import com.edee.bigday.commodity.service.AttrService;
import com.edee.bigday.commodity.service.CategoryService;
import com.edee.bigday.commodity.vo.AttrGroupRelationVo;
import com.edee.bigday.commodity.vo.AttrRespVo;
import com.edee.bigday.commodity.vo.AttrVo;
import com.edee.common.constant.CommodityConstant;
import com.edee.common.utils.PageUtils;
import com.edee.common.utils.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
//        attrEntity.setAttrId(attr.getAttrId());
        BeanUtils.copyProperties(attr, attrEntity);
        //1、保存基本数据：
        this.save(attrEntity);
        //2、保存关联关系：
        if (attr.getAttrType() == CommodityConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            //当属性类型为“基本属性”时，才需要保存分组关系：
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long CatalogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type",
                "base".equalsIgnoreCase(type) ? CommodityConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : CommodityConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (CatalogId != 0) {
            queryWrapper.eq("Catalog_id", CatalogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty("key") && key != null) {
            //上面的&& key != null为后来解决“下一步：设置销售属性”中无法查到销售属性而添加，添加于2021.01.25 17:30，by edee。
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            //将attrEntity的属性拷贝给attrRespVo:
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //设置分类和分组名称：
            //1)先查出关系实体：
            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                //2)由关系实体查到分组id：
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    Long attrGroupId = relationEntity.getAttrGroupId();
                    //3)由分组id查到分组实体：
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    //4)最后设置分组名称：
                    if (attrGroupEntity != null) {
                        //2021.01.25 增加非空判断，by edee。
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            //5)设置分类名称：
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatalogId());
            if (categoryEntity != null) {
                attrRespVo.setCatalogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);

        if (attrEntity.getAttrType() == CommodityConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //1、查询分组信息：
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //2、查询分类信息：
        Long CatalogId = attrEntity.getCatalogId();
        Long[] CatalogPath = categoryService.findCatalogPath(CatalogId);
        respVo.setCatalogPath(CatalogPath);
        //以下两种方法功能相同：
        CategoryEntity categoryEntity = categoryDao.selectById(CatalogId);
        CategoryEntity categoryEntity1 = categoryService.getById(CatalogId);
        if (categoryEntity != null) {
            respVo.setCatalogName(categoryEntity1.getName());
        }
        return respVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == CommodityConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                //1、修改分组关联：
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                //2、新增分组关联：
                relationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据分组id查找关联的所有基本属性
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRaletionAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = relationEntities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //以下两种方法相同？实测未发现不同之处。
        if (attrIds == null || attrIds.size() == 0) {
            //避免空指针异常。
            return null;
        }
        List<AttrEntity> attrEntities = this.listByIds(attrIds);
        Collection<AttrEntity> attrEntities1 = this.listByIds(attrIds);
//        return attrEntities;
        return (List<AttrEntity>) attrEntities1;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //relationDao.delete(new QueryWrapper<>().eq("attr_id",1L).eq("attr_group_id",1L));
        //用上面的删除方法删除多条数据，会发送多次请求。下面采用批量删除方法：
        List<AttrAttrgroupRelationEntity> relationEntities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(relationEntities);
    }

    /**
     * 获取当前分组没有关联的所有属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自身所属分类里的所有属性：
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long CatalogId = attrGroupEntity.getCatalogId();
        //2、当前分组只能关联未被其他分组关联的属性：
        //2.1、查出当前分类下的所有分组：
//        List<AttrGroupEntity> otherGroups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("Catalog_id", CatalogId).ne("attr_group_id", attrgroupId));
        List<AttrGroupEntity> otherGroups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("Catalog_id", CatalogId));
        List<Long> otherGroupIds = otherGroups.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //2.2、查出这些分组关联的属性：
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", otherGroupIds));
        List<Long> relatedAttrIds = relationEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.3、从当前分类的所有属性中排除已被现有分组关联的属性：
//        List<AttrEntity> otherRelatedAttrs = this.baseMapper.selectList(new QueryWrapper<AttrEntity>().eq("Catalog_id", CatalogId).notIn("attr_id", relatedAttrIds));
//        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>().eq("Catalog_id", CatalogId).notIn("attr_id", relatedAttrIds);
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>().eq("Catalog_id", CatalogId).eq("attr_type", CommodityConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
//        if (relatedAttrIds != null || relatedAttrIds.size() > 0) { //应该为&&
        if (relatedAttrIds != null && relatedAttrIds.size() > 0) {
            attrEntityQueryWrapper.notIn("attr_id", relatedAttrIds);
        }
        //下面的代码可以抽取为一个公共方法：
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            attrEntityQueryWrapper.and(wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), attrEntityQueryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        /**
         * SELECT attr_id FROM `cms_attr` WHERE attr_id IN (?) AND search_type=1
         */
        return baseMapper.selectSearchAttrs(attrIds);
    }

}